<?php
// +----------------------------------------------------------------------
// | 有小象汇 自研正版源码 赋能开发者
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 http://www.uxphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 有小象汇并不是自由软件，未经许可不能去掉有小象汇相关版权
// +----------------------------------------------------------------------
// | Author:  有小象汇
// +----------------------------------------------------------------------
/**
 * 公共方法
 *
 */
namespace app\staffapi\controller;


use app\Request;
use app\services\car\CarStaffService;
use app\services\other\UploadService;
use app\services\system\attachment\SystemAttachmentServices;
use think\facade\Cache;
use think\facade\Db;
use com\junziqian\sdk\bean\req\sign\ApplySignReq;
use com\junziqian\sdk\bean\req\sign\ext\SignatoryReq;
use com\junziqian\sdk\util\Assert;
use com\junziqian\sdk\util\CommonUtil;
use com\junziqian\sdk\util\RequestUtils;

/**
 * Class CategoryController
 * @package app\api\controller\v1\store
 */
class PublicController
{
    protected $services;

    public function __construct(CarStaffService $services)
    {
        $this->services = $services;
    }


    /**
     * 获取首页数据
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function get_index_data(Request $request)
    {
        $manager =  $request->managerInfo();
        $res = $this->services->getIndexData($manager);
        return app('json')->success($res);
    }

    /**
     * 图片上传
     * @param Request $request
     * @param SystemAttachmentServices $services
     * @return mixed
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function upload_image(Request $request, SystemAttachmentServices $services)
    {
        $data = $request->postMore([
            ['filename', 'file'],
        ]);
        $data2 = input('ifa','0');
//        $manager_id = $request->managerId();
        $manager_id = 1;
        $uid = 'car_'.$manager_id;
        if (!$data['filename']) return app('json')->fail('参数有误');
//        if (Cache::has('start_uploads_' . $uid) && Cache::get('start_uploads_' . $uid) >= 100) return app('json')->fail('非法操作');
        $upload = UploadService::init(null,$data2);
        $info = $upload->to('car')->validate()->setAuthThumb(false)->move($data['filename']);
        if ($info === false) {
            return app('json')->fail($upload->getError());
        }
        $res = $upload->getUploadInfo();
        $res2 = $res["dir"];
        $services->attachmentAdd($res['name'], $res['size'], $res['type'], $res['dir'], $res['thumb_path'], 1, (int)sys_config('upload_type', 1), $res['time'], 3);
        if (Cache::has('start_uploads_' . $uid))
            $start_uploads = (int)Cache::get('start_uploads_' . $uid);
        else
            $start_uploads = 0;
        $start_uploads++;
        Cache::set('start_uploads_' . $uid, $start_uploads, 86400);
        $res['dir'] = path_to_url($res['dir']);
        if (strpos($res['dir'], 'http') === false) $res['dir'] = $request->domain() . $res['dir'];
        return app('json')->success('图片上传成功!', ['name' => $res['name'], 'url' => $res['dir'],'url2'=>$res2]);
    }


    /**
     * 上传视频
     * @param Request $request
     * @param SystemAttachmentServices $services
     * @return mixed
     */
    public function videoUpload(Request $request, SystemAttachmentServices $services){
        $data = $request->postMore([
            ['chunkNumber', 1],//第几分片
            ['currentChunkSize', 0],//分片大小
            ['chunkSize', 0],//总大小
            ['totalChunks', 1],//分片总数
            ['file', 'file'],//文件
            ['md5', ''],//MD5
            ['filename', 'file'],//文件名称
        ]);
        $data2 = input('ifa','0');
        $manager_id = 1;
        $uid = 'car_'.$manager_id;
        if (!$data['filename']) return app('json')->fail('参数有误');
//        $file = $_FILES['filename'];
//        $data['filename'] = $file['name'];
//        $data['currentChunkSize'] = $file['size'];
//        $data['currentChunkSize'] = $file['size'];
        $upload = UploadService::init(null,$data2);
        $info = $upload->to('car_video')->validate()->setAuthThumb(false)->move($data['filename']);
        if ($info === false) {
            return app('json')->fail($upload->getError());
        }
        $res = $upload->getUploadInfo();
        $res2 = $res["dir"];
        $services->attachmentAdd($res['name'], $res['size'], $res['type'], $res['dir'], $res['thumb_path'], 7, (int)sys_config('upload_type', 1), $res['time'], 3);
        if (Cache::has('start_uploads_' . $uid))
            $start_uploads = (int)Cache::get('start_uploads_' . $uid);
        else
            $start_uploads = 0;
        $start_uploads++;
        Cache::set('start_uploads_' . $uid, $start_uploads, 86400);
        $res['dir'] = path_to_url($res['dir']);
        if (strpos($res['dir'], 'http') === false) $res['dir'] = $request->domain() . $res['dir'];
        return app('json')->success('视频上传成功!', ['name' => $res['name'], 'url' => $res['dir'],'url2'=>$res2]);

    }

    /**
     * 上传视频bak
     * @param Request $request
     * @param SystemAttachmentServices $services
     * @return mixed
     */
    public function videoUpload2(Request $request, SystemAttachmentServices $services){
        $data = $request->postMore([
            ['chunkNumber', 1],//第几分片
            ['currentChunkSize', 0],//分片大小
            ['chunkSize', 0],//总大小
            ['totalChunks', 1],//分片总数
            ['file', 'file'],//文件
            ['md5', ''],//MD5
            ['filename', ''],//文件名称
        ]);
        $data2 = input('ifa','0');

        $file = $_FILES['filename'];
        $data['filename'] = $file['name'];
        $data['currentChunkSize'] = $file['size'];
        $data['currentChunkSize'] = $file['size'];

        $res = $services->videoUpload($data, $file);
        $res['file_path'] = $request->domain() . $res['file_path'];
        return app('json')->success($res);
    }




    /**
     * 获取系统配置
     * @param Request $request
     * @return mixed
     */
    public function systemData(Request $request){
        $injory = ['click'=>false];
        $data['car_injory_list'] = sys_data('car_injory_list');
        $data['service_phone'] = sys_config('service_phone');
        $data['car_charge_type'] = sys_data('car_charge_type');
        array_walk($data['car_injory_list'], function (&$value, $key, $injory){
            $value = array_merge($value, $injory);
        }, $injory);
        $data['wechat_app_name'] = sys_config('wechat_app_name');
        $data['car_staff_avatar'] = sys_config('car_staff_avatar');
        return app('json')->success($data);
    }

    /**
     * 验证店员信息变动
     * @param Request $request
     * @param CarStaffService $service
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkStaffInfo(Request $request,CarStaffService $service){
        $data = $request->getMore([
            ['id',''],
            ['place_id',''],
            ['status',''],
            ['login_name',''],
            ['pwd',''],
            ['is_del','']
        ]);
        return app('json')->success($service->checkStaffInfo($data));
    }

    public function php_jzq_callback(){
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            // 获取POST数据
            $method = $_POST['method'];
            $version = $_POST['version'];
            $timestamp = $_POST['timestamp'];
            $data = json_decode($_POST['data'], true);
            $sign = $_POST['sign'];
            $appKey = $_POST['appkey'];
            // 进行签名验证
            $expectedSign = $this->generateSign($data, $method, $version, $timestamp, $appKey, 'cd2263df4ee5b1c791ed3a3c768cc070'); // 用你的app secret替换 'your-app-secret'
            if ($sign === $expectedSign) {
                // 签名验证通过
                $update = Db::name('contract_entry')->where('Contractnumber',$data["applyNo"])->update(['Sign_status'=>2]);//修改合同为已签约状态
                // 在这里处理请求数据并返回响应
                $response = array(
                    'success' => true
                );
            } else {

                // 签名验证失败
                $response = array(
                    'success' => false,
                    'msg' => '签名验证失败'
                );
            }

            // 返回JSON响应
            header('Content-Type: application/json; charset=utf-8');
            echo json_encode($response);
        } else {
            // 非POST请求，返回错误响应
            header('HTTP/1.1 405 Method Not Allowed');
            echo 'Method Not Allowed';
        }


    }

    // 生成签名的函数
   public function generateSign($data, $method, $version, $timestamp, $appKey, $appSecret) {


       $dataStr = json_encode($data,JSON_UNESCAPED_UNICODE);

       $signString = "data$dataStr" . "method$method" . "version$version" . "timestamp$timestamp" . "appKey$appKey" . "appSecret$appSecret";

       $sign = sha1($signString);

       return $sign;
    }

}
